package edu.pku.sei.transformation.atl.action;

import java.io.FileWriter;
import java.io.IOException;

import edu.pku.sei.transformation.atl.adapter.ATLModuleAdapter;
import edu.pku.sei.transformation.atl.codegen.ATLGenerator;
import edu.pku.sei.transformation.atl.rule.IATLModule;
import edu.pku.sei.transformation.codegen.TransformationExecutionCodegenAdapter;
import edu.pku.sei.transformation.editor.model.execution.TransformationExecution;
import edu.pku.sei.transformation.editor.model.implement.ICodegenElement;
import edu.pku.sei.transformation.editor.views.problem.ProblemView;

public class ATLCodegenAdapter extends TransformationExecutionCodegenAdapter {
	public static final String LANGUAGE = "ATL";
	
	@Override
	public String getLanguage() {
		return LANGUAGE;
	}

	@Override
	public boolean generateCodeToFile(ICodegenElement element, String file) {
		if (!canGenerate(element)) {
			return false;
		} else {
			TransformationExecution transExecution = (TransformationExecution) element;
			
			ProblemView.clearMarks(transExecution.getModel());
			ProblemView.showView();
			IATLModule module = null;
			try {
				module = new ATLModuleAdapter(transExecution);
			} catch (Exception e1) {
				e1.printStackTrace();
				return false;
			}
	
			ATLGenerator generator = new ATLGenerator();
			String content = generator.generate(module);
	
			FileWriter fw;
			try {
				fw = new FileWriter(file);
				fw.write(content, 0, content.length());
				fw.flush();
				fw.close();
				return true;
			} catch (IOException e) {
				e.printStackTrace();
				return false;
			}
		}
	}

	@Override
	public String getFileName(ICodegenElement element) {
		if (element instanceof TransformationExecution)
			return ((TransformationExecution)element).getTransformation().getName() + ".atl";
		else
			return "error";
	}

	

}
